package com.system.service;


import com.system.dao.DaoFactory;
import com.system.dao.UserDao;
import com.system.json.JsonContext;
import com.system.model.User;

import net.sf.json.JSONObject;

public class LoginService {
	private DaoFactory factory=DaoFactory.getInstance();
	private JsonContext context=new JsonContext();
	
	public JSONObject checkoutAdminLogin(String username,String password){
		UserDao userDao=factory.createUserDao();
		User admin=userDao.findByNamePsd(username, password);
		if(admin==null){
			return context.getFailedObject("用户名或密码不正确");
		}
		else if(!admin.getPost().equals("admin")){
			return context.getFailedObject("用户与职位不匹配");
		}
		else{
			User user=new User();
			user.setUsername("admin");user.setPassword("123");
			user.setPost("admin");
			JSONObject json=JSONObject.fromObject(user);
			return context.getSuccessObject("登录成功", json, null);
		}
		
	}
	/**
	 * 修改密码
	 * @param newpsw
	 * @param oldpsw
	 * @param username
	 * @param post
	 * @return
	 */
	public JSONObject checkoutChangePsd(String newpsw,String oldpsw,String username,String post){
		UserDao userDao=factory.createUserDao();
		User user=userDao.findByNamePsd(username, oldpsw);
		if(user==null)
			return context.getFailedObject("原始用户名与密码不匹配");
		else{
			user.setUsername(username);
			user.setPassword(newpsw);
			user.setPost(post);
			boolean res=userDao.modify(user);
			if(!res)
				return context.getFailedObject("修改失败");
			else
				return context.getSuccessObject("修改成功", null, null);
		}
	}
	
	public JSONObject checkoutTeaLogin(String username,String password){
		UserDao userDao=factory.createUserDao();
		User teacher=userDao.findByNamePsd(username, password);
		if(teacher==null){
			return context.getFailedObject("用户名或密码不正确");
		}
		else if(!teacher.getPost().equals("teacher")){
			return context.getFailedObject("用户与职位不匹配");
		}
		else{
			return context.getSuccessObject("登录成功", null, null);
		}
	}
	
	public JSONObject checkoutStuLogin(String username,String password){
		UserDao userDao=factory.createUserDao();
		User student=userDao.findByNamePsd(username, password);
		if(student==null){
			return context.getFailedObject("用户名或密码不正确");
		}
		else if(!student.getPost().equals("student")){
			return context.getFailedObject("用户与职位不匹配");
		}
		else{
			return context.getSuccessObject("登录成功", null, null);
		}
	}
}
